<?php

namespace app\admin\controller;
vendor('wechat/autoload');
use app\admin\builder\ConfigBuilder;
use app\admin\builder\ListBuilder;
use app\admin\core\Module;
use \app\admin\model\Mp as MpModel;
use app\admin\model\MpReply;
use app\common\model\Config;
use EasyWeChat\Foundation\Application;
use think\Controller;
use think\Request;
use think\Url;

class Mp extends Admin  {

    /**
     * @return Application
     */
    private function getApp() {
        $selectedMp = get_selected_mp();
        if($selectedMp === null) {
            $this->error("请先选择微信公众号",Url::build('admin/Mp/mpList'));
        }
        $options = array_merge(
            \think\Config::get('mp_options'),
            [
                'app_id'=> $selectedMp['appid'],
                'secret'=> $selectedMp['appsecret'],
                'token' => $selectedMp['token'],
            ]
        );
        return new Application($options);
    }
    public function mpReplyList() {
        $data = MpReply::all();

        $typeMap = [
            '文本'=>MpReply::TYPE_TEXT,
            '模块'=>MpReply::TYPE_MODULE,
            '图片'=>MpReply::TYPE_IMAGE,
            '图文'=>MpReply::TYPE_NEWS,
            '监听器'=>MpReply::TYPE_MESSAGE_LISTENER,
            '默认消息处理'=>MpReply::TYPE_DEFAULT_MESSAGE_HANDLER
        ];

        $builder = new ListBuilder();
        return $builder
            ->title("回复管理")
            ->buttonNew(Url::build('editReplyText'),"添加文本回复")
            ->buttonNew(Url::build('editReplyImage'),'添加图片回复')
            ->buttonNew(Url::build('editReplyNews'),'添加图文回复')
            ->buttonNew(Url::build('editReplyModule'),"添加模块回复")
            ->buttonNew(Url::build('editMessageListener'),'添加消息监听')
            ->buttonNew(Url::build('editDefaultMessageHandler'),'添加默认消息处理')
            ->buttonDelete(Url::build('delReply'))
            ->keyText('keyword','关键词')
            ->keyText('type','回复类型',$typeMap)
            ->keyDoAction(function ($data){
                switch ($data['type']) {
                    case MpReply::TYPE_TEXT:
                        return str_replace('###',$data['id'],urldecode(Url::build('editReplyText',['id'=>'###'])));
                        break;
                    case MpReply::TYPE_MODULE:
                        return str_replace('###',$data['id'],urldecode(Url::build('editReplyModule',['id'=>'###'])));
                        break;
                    case MpReply::TYPE_IMAGE:
                        return str_replace('###',$data['id'],urldecode(Url::build('editReplyImage',['id'=>'###'])));
                        break;
                    case MpReply::TYPE_NEWS:
                        return str_replace('###',$data['id'],urldecode(Url::build('editReplyNews',['id'=>'###'])));
                        break;
                    case MpReply::TYPE_MESSAGE_LISTENER:
                        return str_replace('###',$data['id'],urldecode(Url::build('editMessageListener',['id'=>'###'])));
                        break;
                    case MpReply::TYPE_DEFAULT_MESSAGE_HANDLER:
                        return str_replace('###',$data['id'],urldecode(Url::build('editDefaultMessageHandler',['id'=>'###'])));
                        break;
                }
            },'编辑',false)
            ->data($data)
            ->fetch();
    }
    public function editDefaultMessageHandler(Request $request,$id = null) {
        if($request->isPost()) {
            $content = $request->param('content');
            if($id === null) {
                //创建
                if(MpReply::addDefaultMessageHandler($content)) {
                    $this->success('创建成功',Url::build('mpReplyList'));
                }else {
                    $this->error('创建失败');
                }
            }else {
                // 修改
                $reply = MpReply::get($id);
                $reply['content'] = $content;
                if($reply->save()) {
                    $this->success("修改成功",Url::build('mpReplyList'));
                }else {
                    $this->error('修改失败');
                }
            }
        }else {
            $data = [];
            if($id!==null) {
                $data = MpReply::get($id);
            }
            $builder = new ConfigBuilder();
            return $builder
                ->title('默认消息处理')
                ->keyText('content','模块名')
                ->data($data)
                ->buttonSubmit()
                ->buttonBack()
                ->fetch();
        }
    }
    public function editMessageListener(Request $request,$id = null) {
        if($request->isPost()) {
            $content = $request->param('content');
            if($id === null) {
                // 创建
                if(MpReply::addMessageListener($content)) {
                    $this->success('创建成功',Url::build('mpReplyList'));
                }else {
                    $this->error('创建失败');
                }
            }else {
                // 修改
                $reply = MpReply::get($id);
                $reply['content'] = $content;
                if($reply->save()) {
                    $this->success('修改成功',Url::build('mpReplyList'));
                }else {
                    $this->error('修改失败');
                }
            }
        }else {
            $data = [];
            if($id !== null) {
                $data = MpReply::get($id);
            }
            $builder = new ConfigBuilder();
            return $builder
                ->title('消息监听')
                ->keyText('content','模块名')
                ->data($data)
                ->buttonSubmit()
                ->buttonBack()
                ->fetch();
        }
    }
    public function editReplyNews(Request $request, $id = null) {
        if($request->isPost()) {
            $keyword = $request->param('keyword');
            $json['title'] = $request->param('title');
            $json['cover'] = string_to_img_array($request->param('cover'))[0];
            $json['desc'] = $request->param('desc');
            $json['url'] = $request->param('url');
            $content = json_encode($json);
            if($id === null) {
                // 创建
                if(MpReply::addReplyNews($keyword,$content)){
                    $this->success('创建成功',Url::build('mpReplyList'));
                }else {
                    $this->error('关键词重复');
                }
            }else {
                // 修改
                $reply = MpReply::get($id);
                $reply['keyword'] = $keyword;
                $reply['content'] = $content;
                if($reply->save()) {
                    $this->success('创建成功',Url::build('mpReplyList'));
                }else {
                    $this->error('关键词重复');
                }
            }
        }else {
            $data = [];
            if($id !== null) {
                $data = MpReply::get($id);
                $data = $data->toArray();
                $data = array_merge($data,json_decode($data['content'],true));
            }
            $builder = new ConfigBuilder();
            return $builder
                ->title('图文回复')
                ->keyText('keyword','关键词')
                ->keyText('title','图文标题','可以不写')
                ->keyText('url','跳转','可以不写')
                ->keySingleImage('cover','图文封面','只能弄一张图片，可以不写')
                ->keyTextArea('desc','图文描述','可以不写')
                ->data($data)
                ->buttonSubmit()
                ->buttonBack()
                ->fetch();
        }
    }
    public function editReplyImage(Request $request,$id = null) {
        if($request->isPost()) {
            $keyword = $request->param('keyword');
            $content = $request->param('content');
            $content = string_to_img_array($content)[0];
            if($id === null) {
                // 添加
                if(MpReply::addReplyImage($keyword,$content)) {
                    $this->success('添加成功');
                }else {
                    $this->error('关键词重复');
                }
            }else {
                // 修改
                $reply = MpReply::get($id);
                $reply['keyword'] = $keyword;
                $reply['content'] = $content;
                if($reply->save()===false) {
                    $this->error('关键词重复');
                }else {
                    $this->success("修改成功",Url::build('mpReplyList'));
                }
            }
        }else {
            $data = [];
            if($id !== null) {
                $data = MpReply::get($id);
            }
            $builder = new ConfigBuilder();
            return $builder
                ->title("图文回复")
                ->keyText('keyword','关键字')
                ->keySingleImage('content','图片','注意这里只能上传一张图片')
                ->buttonSubmit()
                ->buttonBack()
                ->data($data)
                ->fetch();
        }
    }
    public function delReply($ids) {
        if(MpReply::destroy($ids)) {
            $this->success('删除成功');
        }else {
            $this->error("删除失败");
        }
    }
    public function editReplyModule(Request $request,$id = null) {
        if($request->isPost()) {
            $keyword = $request->param('keyword');
            $content = $request->param('content');
            if($id === null) {
                // 创建
                if(MpReply::addReplyModule($keyword,$content)) {
                    $this->success("创建成功",Url::build('mpReplyList'));
                }else {
                    $this->error('关键词重复');
                }
            }else {
                // 修改
                $reply = MpReply::get($id);
                $reply['keyword'] = $keyword;
                $reply['content'] = $content;
                if($reply->save()) {
                    $this->success("修改成功",Url::build('mpReplyList'));
                }else {
                    $this->error('关键词重复');
                }
            }
        }else {
            $data = [];
            if($id!==null) {
                $data = MpReply::get($id);
            }
            $builder = new ConfigBuilder();
            return $builder
                ->title("模块回复")
                ->keyText('keyword','关键词')
                ->keyText('content','模块名','例如:index')
                ->data($data)
                ->buttonSubmit()
                ->buttonBack()
                ->fetch();
        }
    }
    public function editReplyText(Request $request,$id = null) {
        if($request->isPost()) {
            $keyword = $request->param('keyword');
            $content = $request->param('content');
            if($id === null) {
                // 创建
                if(MpReply::addReplyText($keyword,$content)) {
                    $this->success("创建成功",Url::build('mpReplyList'));
                }else {
                    $this->error("关键词重复");
                }
            }else {
                // 修改
                $reply = MpReply::get($id);
                $reply['keyword'] = $keyword;
                $reply['content'] = $content;
                if($reply->save()) {
                    $this->success("修改成功",Url::build('mpReplyList'));
                }else {
                    $this->error("关键词重复");
                }
            }
        }else {
            $data = [];
            if($id !== null) {
                $data = MpReply::get($id);
            }
            $builder = new ConfigBuilder();
            return $builder
                ->title("自动回复")
                ->keyText('keyword','关键字')
                ->keyTextArea('content','文本内容')
                ->buttonSubmit()
                ->buttonBack()
                ->data($data)
                ->fetch();
        }
    }
    public function mpBind($id) {
        Config::setConfig('WEIPETER_MP_BIND',$id);
        $this->success('绑定成功');
    }
    public function mpList() {
        $data = MpModel::getList();

        $builder = new ListBuilder();
        return $builder
            ->title("公众号管理")
            ->keyText("alias","昵称")
            ->keyText("interface","url接口")
            ->keyText('create_time','创建时间')
            ->keyDoAction(urldecode(Url::build('mpSelect',['id'=>'###'])),'选择')
            ->keyDoAction(urldecode(Url::build('mpBind',['id'=>'###'])),'绑定')
            ->keyDoAction(urldecode(Url::build('mpNew',['id'=>'###'])),'编辑',false)
            ->keyDoAction(urldecode(Url::build('mpDel',['id'=>'###'])),'删除')
            ->buttonNew(Url::build('mpNew'))
            ->data($data)
            ->fetch();
    }
    public function mpSelect($id) {
        if(MpModel::selectMp($id)) {
            $this->success('选择成功');
        }else {
            $this->error("选择失败");
        }
    }
    public function mpDel($id) {
        if(MpModel::destroy($id)){
            MpModel::deselectMp();
            $this->success("删除成功");
        }else {
            $this->error("删除失败");
        }
    }
    public function mpNew(Request $request) {
        if($request->isPost()) {
            if(MpModel::createMp($request->param()) === false) {
                $this->error('失败');
            }else {
                $this->success('成功',Url::build('mpList'));
            }
        }else {
            $data = [];
            if($id = $request->param('id')) {
                $data = MpModel::get($id);
            }
            $builder = new ConfigBuilder();
            return $builder
                ->title("公众号")
                ->keyText('alias','昵称','没有实际作用，用来标识公众号作用的名称')
                ->keyText('originid',"原始id")
                ->keyText('appid',"appId")
                ->keyText('appsecret','appSecret')
                ->keyText('token','token')
                ->buttonSubmit()
                ->buttonBack()
                ->data($data)
                ->fetch();
        }
    }
}